package com.jz.yanshe.ui;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.jz.yanshe.base.BaseActivity;
import com.jz.yanshe.util.PreferencesHelper;
import com.fynn.fluidlayout.FluidLayout;

import butterknife.BindView;
import butterknife.OnClick;
import com.jz.yanshe.R;
/**
 * Created by Administrator on 2018/3/15.
 */

public class SearchActivity extends BaseActivity {

    @BindView(R.id.search_history_container)
    FluidLayout search_history_container;

    @BindView(R.id.btn_search)
    EditText btn_search;

    String history;

    @Override
    protected void initViews() {

        if (history != null && !history.equals("")) {
            String s[] = history.split(",");
            for (int i = 0; i < s.length; i++) {
                View view = getLayoutInflater().inflate(R.layout.item_search, null);
                final TextView tv_name = view.findViewById(R.id.tv_name);
                tv_name.setText(s[i]);
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putString("searchText", tv_name.getText().toString().trim());
                        startActivity(SearchListActivity.class, bundle);
                    }
                });
                search_history_container.addView(view);
            }
        }

        btn_search.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == event.KEYCODE_ENTER) {
                    if (event.getAction() == KeyEvent.ACTION_UP) {
                        if (btn_search.getText().toString().trim().equals("")) {
                            Toast.makeText(SearchActivity.this, "请输入查询关键字", Toast.LENGTH_SHORT).show();
                            return false;
                        }
                        PreferencesHelper.getInstance().set(SearchActivity.this, "history", history + btn_search.getText().toString().trim() + ",");
                        Bundle bundle = new Bundle();
                        bundle.putString("searchText", btn_search.getText().toString().trim());
                        startActivity(SearchListActivity.class, bundle);
                    }
                }
                return false;
            }
        });
    }

    @Override
    protected void initData() {
        history = PreferencesHelper.getInstance().getString(this, "history");

    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_search;
    }

    @OnClick(R.id.btn_del)
    void btn_del() {
        search_history_container.removeAllViews();
        PreferencesHelper.getInstance().set(SearchActivity.this, "history", "");

    }


}
